package com.example.note.controller;

import com.example.note.model.NoteInfo;
import com.example.note.model.Result;
import com.example.note.service.NoteService;
import com.example.note.model.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: Home-pc
 */
@Slf4j
@RequestMapping("/note")
@RestController
public class NoteController {

    @Autowired
    private NoteService noteService;
    /**
     * 获取笔记列表
     */
    @RequestMapping("/getlist")
    public List<NoteInfo> getNoteList(){
        return  noteService.getNoteList();
    }

    /**
     * 获取笔记详情页
     */
    @RequestMapping("/getNoteDetail")
    public NoteInfo getNoteDetail(Integer noteId,HttpServletRequest request){
        NoteInfo noteInfo = noteService.getNoteDetail(noteId);
        //判断作者是否为登录用户,从登录用户的token中拿到用户的id和笔记信息中的用户的id进行对比

        String token = request.getHeader("user_token");
        log.info("45645" +token);
        Integer userId = JwtUtils.getUserIdFromToken(token);
        if(userId != null && userId == noteInfo.getUserId()){
            noteInfo.setLoginUser(true);
        }
        return noteInfo;
    }

    /**
     * 发布笔记
     */
    @RequestMapping("/add")
    public Result publishNote(String title, String content, HttpServletRequest request){
        //需要userId，title，content
        //从token中获取userId
        String token = request.getHeader("user_token");
        Integer userId = JwtUtils.getUserIdFromToken(token);
        if(userId == null || userId<0){
            return  Result.fail("用户未登录",false);

        }
        //插入笔记
        NoteInfo noteInfo = new NoteInfo();
        noteInfo.setUserId(userId);
        noteInfo.setTitle(title);
        noteInfo.setContent(content);
        noteService.insertNote(noteInfo);
        return  Result.success(true);
    }

    /**
     * 修改/编辑笔记
     */
    @RequestMapping("/update")
    public boolean updateNote(Integer id ,String title,String content){
        //需要笔记的标题和内容，以及被更新的笔记的id
        NoteInfo noteInfo = new NoteInfo();
        noteInfo.setTitle(title);
        noteInfo.setContent(content);
        noteInfo.setId(id);

        noteService.updateNote(noteInfo);
        return true;
    }
}
